<template>
  <div class="chat-container">
    <!-- 消息显示区域 -->
    <div ref="messageArea" class="message-area">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.sender]"
      >
        <div class="avatar" v-if="msg.sender === 'bot'">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <path d="M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M13,17h-2v-2h2V17z M15,13h-2v-4h-2V7h4V13z"/>
          </svg>
        </div>
        <div class="content">
          <div class="sender-name">{{ msg.sender === 'user' ? '您' : '法律助手' }}</div>
          <div class="text" v-html="formatBotMessage(msg.text)"></div>
          <div class="timestamp">{{ formatTime(msg.timestamp) }}</div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="message bot">
        <div class="avatar">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <path d="M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M13,17h-2v-2h2V17z M15,13h-2v-4h-2V7h4V13z"/>
          </svg>
        </div>
        <div class="content">
          <div class="sender-name">法律助手</div>
          <div class="text">
            <div class="loading-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <textarea
          v-model="userInput"
          placeholder="请输入法律问题..."
          @keyup.enter.exact="sendMessage"
          ref="inputField"
      ></textarea>
      <button @click="sendMessage" :disabled="isLoading">
        <svg v-if="!isLoading" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
          <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
        </svg>
        <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="spinner">
          <path d="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z"/>
        </svg>
      </button>
    </div>

    <!-- 免责声明 -->
    <div class="disclaimer">
      免责声明：本AI助手提供的建议仅供参考，不构成正式法律意见
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue';
import { getLegalAdvice } from '@/api/ai';

// 响应式数据
const messages = ref([]);
const userInput = ref('');
const isLoading = ref(false);
const messageArea = ref(null);
const inputField = ref(null);

// 初始问候语
onMounted(() => {
  addMessage({
    text: '您好！我是法律AI助手，请提出您关心的法律问题',
    sender: 'bot',
    timestamp: new Date()
  });

  // 自动聚焦输入框
  setTimeout(() => {
    if (inputField.value) inputField.value.focus();
  }, 300);
});

// 添加消息到聊天记录
function addMessage(message) {
  messages.value.push({
    ...message,
    timestamp: message.timestamp || new Date()
  });

  // 滚动到底部
  nextTick(() => {
    if (messageArea.value) {
      messageArea.value.scrollTop = messageArea.value.scrollHeight;
    }
  });
}

// 格式化AI消息
function formatBotMessage(text) {
  // 查找并高亮法律条文引用
  const lawRegex = /《([^》]+)》第([\d零一二三四五六七八九十百千]+)条/g;
  return text.replace(lawRegex, '<span class="law-reference">《$1》第$2条</span>');
}

// 格式化时间
function formatTime(date) {
  return new Date(date).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

// 发送消息
async function sendMessage() {
  if (!userInput.value.trim() || isLoading.value) return;

  // 添加用户消息
  const userMsg = {
    text: userInput.value,
    sender: 'user',
    timestamp: new Date()
  };
  addMessage(userMsg);

  const userQuery = userInput.value;
  userInput.value = '';
  isLoading.value = true;

  try {
    // 准备消息历史 (只保留最近的4条)
    const recentHistory = messages.value
        .slice(-4)
        .filter(msg => msg.sender !== 'system') // 排除系统消息
        .map(msg => ({
          role: msg.sender === 'user' ? 'user' : 'assistant',
          content: msg.text
        }));

    // 获取法律建议
    const aiResponse = await getLegalAdvice(userQuery, recentHistory);

    // 添加AI回复
    addMessage({
      text: aiResponse,
      sender: 'bot',
      timestamp: new Date()
    });
  } catch (error) {
    console.error('获取AI回复失败:', error);
    addMessage({
      text: '服务暂时不可用，请稍后再试',
      sender: 'bot'
    });
  } finally {
    isLoading.value = false;

    // 重新聚焦输入框
    nextTick(() => {
      if (inputField.value) inputField.value.focus();
    });
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  max-width: 100%;
  margin: 0 auto;
  background-color: #ffffff;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  overflow: hidden;
}

.message-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9fafb;
}

.message {
  display: flex;
  margin-bottom: 25px;
  animation: fadeIn 0.4s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(15px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.user {
  justify-content: flex-end;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #4a8eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.message.user .avatar {
  background-color: #8a5cf6;
}

.avatar svg {
  width: 22px;
  height: 22px;
  fill: currentColor;
}

.content {
  max-width: 85%;
}

.sender-name {
  font-size: 13px;
  color: #666;
  margin-bottom: 5px;
  font-weight: 600;
}

.message.user .sender-name {
  text-align: right;
}

.text {
  font-size: 16px;
  line-height: 1.5;
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message.user .text {
  background-color: #d6e9ff;
  border-radius: 18px 18px 0 18px;
}

.message.bot .text {
  background-color: #ffffff;
  border: 1px solid #e8ecf1;
  border-radius: 18px 18px 18px 0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
}

.law-reference {
  color: #1a73e8;
  font-weight: bold;
  background-color: rgba(26, 115, 232, 0.08);
  padding: 0 4px;
  border-radius: 4px;
}

.timestamp {
  font-size: 12px;
  color: #999;
  margin-top: 6px;
}

.message.user .timestamp {
  text-align: right;
}

.input-area {
  display: flex;
  padding: 15px;
  border-top: 1px solid #f0f0f0;
  background-color: #ffffff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
}

.input-area textarea {
  flex: 1;
  padding: 14px 18px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  resize: none;
  height: 56px;
  font-size: 16px;
  transition: all 0.25s;
  background-color: #f8fafc;
}

.input-area textarea:focus {
  outline: none;
  border-color: #4a8eff;
  box-shadow: 0 0 0 2px rgba(74, 142, 255, 0.2);
}

.input-area button {
  margin-left: 12px;
  width: 56px;
  height: 56px;
  background-color: #4a8eff;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.input-area button:disabled {
  background-color: #a0c5f0;
  cursor: not-allowed;
}

.input-area button:not(:disabled):hover {
  background-color: #3a7bc8;
}

.input-area svg {
  width: 24px;
  height: 24px;
  fill: currentColor;
}

.spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.disclaimer {
  text-align: center;
  font-size: 12px;
  color: #777;
  padding: 12px;
  background-color: #fff8e1;
  border-top: 1px solid #ffecb3;
}

/* 加载动画样式 */
.loading-dots {
  display: inline-flex;
  align-items: center;
  height: 24px;
  padding-left: 5px;
}

.loading-dots span {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #999;
  margin: 0 3px;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0.6);
  }
  40% {
    transform: scale(1);
  }
}
</style>